package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;


/**
 * @author Triin & Matu
 *
 */
public class DBConnection{
	ResultSet resultSet;
	String sql;
	String url = "";
	String pwd = "";
	String usr = "";
	Statement st;
	Connection db;
	
	public void connect(){
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("DBConnection");
			this.url = bundle.getString("url");
			this.usr = bundle.getString("usr");
			this.pwd = bundle.getString("pwd");
			Class.forName(bundle.getString("Driver"));

			this.db = DriverManager.getConnection(this.url, this.usr, this.pwd);
			this.st = this.db.createStatement();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	/**
	 * Only for SELECT-statements!
	 * @param sql select statement
	 * @return
	 * @throws SQLException
	 */
	public ResultSet executeQuery(String sql) throws SQLException{
		connect();
		resultSet = st.executeQuery(sql);
		closeConnection();
		return resultSet;
	}
	public void closeConnection(){
		try {
			db.close();
			System.out.println("Connection closed");
		} catch (SQLException e) {
			System.out.println("Failed to close connection");
		}
	}
	public Connection getConnection(){
		return this.db;
	}
}
